"""
协作服务

提供协作相关的功能，包括：
- 协作邀请管理
- 实时协作编辑
- 版本控制
- 冲突解决
"""
import json
import uuid
from typing import Dict, List, Any, Optional
from datetime import datetime
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
collaboration_logger = logging.getLogger('collaboration_service')


class CollaborationService:
    """协作服务类"""
    
    def __init__(self):
        # 模拟数据存储
        self.invitations = {}
        self.collaborations = {}
        self.versions = {}
        self.edit_sessions = {}
        self.conflicts = {}
    
    def send_invitation(self, sender_id: str, invitation_data: Dict[str, Any]) -> Dict[str, Any]:
        """发送协作邀请"""
        try:
            invitation_id = str(uuid.uuid4())
            
            invitation = {
                'invitation_id': invitation_id,
                'sender_id': sender_id,
                'project_id': invitation_data.get('project_id', ''),
                'invitee_email': invitation_data.get('invitee_email', ''),
                'role': invitation_data.get('role', 'collaborator'),
                'permissions': invitation_data.get('permissions', ['read']),
                'message': invitation_data.get('message', ''),
                'status': 'pending',
                'sent_at': datetime.now().isoformat(),
                'expires_at': (datetime.now().replace(day=datetime.now().day + 7)).isoformat()
            }
            
            self.invitations[invitation_id] = invitation
            
            collaboration_logger.info(f"协作邀请发送成功: {invitation_id}")
            
            return {
                'success': True,
                'invitation_id': invitation_id,
                'message': '邀请发送成功'
            }
            
        except Exception as e:
            collaboration_logger.error(f"发送邀请失败: {str(e)}")
            return {
                'success': False,
                'error': str(e)
            }
    
    def accept_invitation(self, user_id: str, invitation_id: str) -> Dict[str, Any]:
        """接受协作邀请"""
        try:
            if invitation_id not in self.invitations:
                return {'success': False, 'error': '邀请不存在'}
            
            invitation = self.invitations[invitation_id]
            
            if invitation['status'] != 'pending':
                return {'success': False, 'error': '邀请已处理'}
            
            # 更新邀请状态
            invitation['status'] = 'accepted'
            invitation['accepted_at'] = datetime.now().isoformat()
            invitation['accepted_by'] = user_id
            
            # 创建协作关系
            collaboration_id = str(uuid.uuid4())
            collaboration = {
                'collaboration_id': collaboration_id,
                'project_id': invitation['project_id'],
                'collaborator_id': user_id,
                'role': invitation['role'],
                'permissions': invitation['permissions'],
                'joined_at': datetime.now().isoformat(),
                'status': 'active'
            }
            
            self.collaborations[collaboration_id] = collaboration
            
            collaboration_logger.info(f"协作邀请接受成功: {invitation_id}")
            
            return {
                'success': True,
                'collaboration_id': collaboration_id,
                'message': '邀请接受成功'
            }
            
        except Exception as e:
            collaboration_logger.error(f"接受邀请失败: {str(e)}")
            return {
                'success': False,
                'error': str(e)
            }
    
    def decline_invitation(self, user_id: str, invitation_id: str) -> Dict[str, Any]:
        """拒绝协作邀请"""
        try:
            if invitation_id not in self.invitations:
                return {'success': False, 'error': '邀请不存在'}
            
            invitation = self.invitations[invitation_id]
            
            if invitation['status'] != 'pending':
                return {'success': False, 'error': '邀请已处理'}
            
            # 更新邀请状态
            invitation['status'] = 'declined'
            invitation['declined_at'] = datetime.now().isoformat()
            invitation['declined_by'] = user_id
            
            collaboration_logger.info(f"协作邀请拒绝: {invitation_id}")
            
            return {
                'success': True,
                'message': '邀请已拒绝'
            }
            
        except Exception as e:
            collaboration_logger.error(f"拒绝邀请失败: {str(e)}")
            return {
                'success': False,
                'error': str(e)
            }
    
    def collaborative_edit(self, project_id: str, edit_data: Dict[str, Any]) -> Dict[str, Any]:
        """协作编辑"""
        try:
            edit_id = str(uuid.uuid4())
            
            edit_session = {
                'edit_id': edit_id,
                'project_id': project_id,
                'editor': edit_data.get('editor', ''),
                'section': edit_data.get('section', ''),
                'content': edit_data.get('content', ''),
                'edit_type': edit_data.get('edit_type', 'update'),
                'timestamp': datetime.now().isoformat(),
                'status': 'completed'
            }
            
            self.edit_sessions[edit_id] = edit_session
            
            collaboration_logger.info(f"协作编辑完成: {edit_id}")
            
            return {
                'success': True,
                'edit_id': edit_id,
                'message': '编辑完成'
            }
            
        except Exception as e:
            collaboration_logger.error(f"协作编辑失败: {str(e)}")
            return {
                'success': False,
                'error': str(e)
            }
    
    def create_version(self, project_id: str, version_message: str, creator_id: str) -> Dict[str, Any]:
        """创建版本"""
        try:
            version_id = str(uuid.uuid4())
            
            version = {
                'version_id': version_id,
                'project_id': project_id,
                'version_number': len([v for v in self.versions.values() if v['project_id'] == project_id]) + 1,
                'message': version_message,
                'creator_id': creator_id,
                'created_at': datetime.now().isoformat(),
                'changes': {
                    'files_modified': 3,
                    'lines_added': 150,
                    'lines_deleted': 25
                },
                'status': 'active'
            }
            
            self.versions[version_id] = version
            
            collaboration_logger.info(f"版本创建成功: {version_id}")
            
            return {
                'success': True,
                'version_id': version_id,
                'version': version
            }
            
        except Exception as e:
            collaboration_logger.error(f"版本创建失败: {str(e)}")
            return {
                'success': False,
                'error': str(e)
            }
    
    def resolve_conflict(self, project_id: str, conflict_data: Dict[str, Any]) -> Dict[str, Any]:
        """解决冲突"""
        try:
            conflict_id = str(uuid.uuid4())
            
            conflict = {
                'conflict_id': conflict_id,
                'project_id': project_id,
                'section': conflict_data.get('section', ''),
                'conflicts': conflict_data.get('conflicts', []),
                'resolution_strategy': conflict_data.get('resolution', 'manual'),
                'resolved_content': self._resolve_conflict_content(
                    conflict_data.get('conflicts', []),
                    conflict_data.get('resolution', 'manual')
                ),
                'resolved_at': datetime.now().isoformat(),
                'status': 'resolved'
            }
            
            self.conflicts[conflict_id] = conflict
            
            collaboration_logger.info(f"冲突解决完成: {conflict_id}")
            
            return {
                'success': True,
                'conflict_id': conflict_id,
                'resolved_content': conflict['resolved_content']
            }
            
        except Exception as e:
            collaboration_logger.error(f"冲突解决失败: {str(e)}")
            return {
                'success': False,
                'error': str(e)
            }
    
    def _resolve_conflict_content(self, conflicts: List[Dict[str, Any]], strategy: str) -> str:
        """解决冲突内容"""
        if not conflicts:
            return ""
        
        if strategy == 'merge':
            # 合并所有冲突内容
            merged_content = []
            for conflict in conflicts:
                merged_content.append(f"[{conflict['user']}]: {conflict['content']}")
            return "\n".join(merged_content)
        
        elif strategy == 'first_wins':
            # 第一个版本获胜
            return conflicts[0]['content']
        
        elif strategy == 'last_wins':
            # 最后一个版本获胜
            return conflicts[-1]['content']
        
        else:
            # 默认合并策略
            return " | ".join([conflict['content'] for conflict in conflicts])
    
    def get_project_collaborators(self, project_id: str) -> Dict[str, Any]:
        """获取项目协作者"""
        try:
            collaborators = [
                collab for collab in self.collaborations.values()
                if collab['project_id'] == project_id and collab['status'] == 'active'
            ]
            
            return {
                'success': True,
                'collaborators': collaborators,
                'count': len(collaborators)
            }
            
        except Exception as e:
            collaboration_logger.error(f"获取协作者失败: {str(e)}")
            return {
                'success': False,
                'error': str(e)
            }
    
    def get_user_invitations(self, user_id: str) -> Dict[str, Any]:
        """获取用户的邀请"""
        try:
            user_invitations = [
                invitation for invitation in self.invitations.values()
                if invitation['invitee_email'].startswith(user_id) or invitation['sender_id'] == user_id
            ]
            
            return {
                'success': True,
                'invitations': user_invitations,
                'count': len(user_invitations)
            }
            
        except Exception as e:
            collaboration_logger.error(f"获取邀请失败: {str(e)}")
            return {
                'success': False,
                'error': str(e)
            }
    
    def get_project_versions(self, project_id: str) -> Dict[str, Any]:
        """获取项目版本"""
        try:
            project_versions = [
                version for version in self.versions.values()
                if version['project_id'] == project_id
            ]
            
            # 按版本号排序
            project_versions.sort(key=lambda x: x['version_number'], reverse=True)
            
            return {
                'success': True,
                'versions': project_versions,
                'count': len(project_versions)
            }
            
        except Exception as e:
            collaboration_logger.error(f"获取版本失败: {str(e)}")
            return {
                'success': False,
                'error': str(e)
            }
    
    def get_edit_history(self, project_id: str) -> Dict[str, Any]:
        """获取编辑历史"""
        try:
            edit_history = [
                edit for edit in self.edit_sessions.values()
                if edit['project_id'] == project_id
            ]
            
            # 按时间排序
            edit_history.sort(key=lambda x: x['timestamp'], reverse=True)
            
            return {
                'success': True,
                'edit_history': edit_history,
                'count': len(edit_history)
            }
            
        except Exception as e:
            collaboration_logger.error(f"获取编辑历史失败: {str(e)}")
            return {
                'success': False,
                'error': str(e)
            }
    
    def remove_collaborator(self, project_id: str, collaborator_id: str) -> Dict[str, Any]:
        """移除协作者"""
        try:
            removed_count = 0
            
            for collab_id, collab in self.collaborations.items():
                if (collab['project_id'] == project_id and 
                    collab['collaborator_id'] == collaborator_id and 
                    collab['status'] == 'active'):
                    
                    collab['status'] = 'removed'
                    collab['removed_at'] = datetime.now().isoformat()
                    removed_count += 1
            
            if removed_count > 0:
                collaboration_logger.info(f"协作者移除成功: {collaborator_id}")
                return {
                    'success': True,
                    'message': '协作者移除成功'
                }
            else:
                return {
                    'success': False,
                    'error': '协作者不存在或已移除'
                }
            
        except Exception as e:
            collaboration_logger.error(f"移除协作者失败: {str(e)}")
            return {
                'success': False,
                'error': str(e)
            }
    
    def update_collaborator_permissions(self, project_id: str, collaborator_id: str, 
                                      new_permissions: List[str]) -> Dict[str, Any]:
        """更新协作者权限"""
        try:
            updated_count = 0
            
            for collab_id, collab in self.collaborations.items():
                if (collab['project_id'] == project_id and 
                    collab['collaborator_id'] == collaborator_id and 
                    collab['status'] == 'active'):
                    
                    collab['permissions'] = new_permissions
                    collab['permissions_updated_at'] = datetime.now().isoformat()
                    updated_count += 1
            
            if updated_count > 0:
                collaboration_logger.info(f"协作者权限更新成功: {collaborator_id}")
                return {
                    'success': True,
                    'message': '权限更新成功'
                }
            else:
                return {
                    'success': False,
                    'error': '协作者不存在'
                }
            
        except Exception as e:
            collaboration_logger.error(f"权限更新失败: {str(e)}")
            return {
                'success': False,
                'error': str(e)
            }
    
    def get_service_status(self) -> Dict[str, Any]:
        """获取服务状态"""
        return {
            'service_name': 'CollaborationService',
            'status': 'running',
            'invitations_count': len(self.invitations),
            'active_collaborations_count': len([c for c in self.collaborations.values() if c['status'] == 'active']),
            'versions_count': len(self.versions),
            'edit_sessions_count': len(self.edit_sessions),
            'conflicts_resolved_count': len(self.conflicts),
            'last_activity': datetime.now().isoformat()
        }